<template>
  <view>
    <view class="list-wrap">
      <scroll-view :scroll-top="scrollTop" scroll-y="true" class="list" @scroll="scroll">
        <view class="__margin-top"></view>
        <slider-item class="section" v-for="(item, index) in experovermsg" :key="index" @click="toggleImage(index,item)"
                     @swipe="toEdit">
          <view class="section-content">
            <view class="left">
              <uni-icons v-if="edit&&!item.selected" type="circle" size="40rpx"/>
              <uni-icons v-if="edit&&item.selected" type="circle-filled" size="40rpx"/>
              <image class="icon"
                     src="../../static/images/6a099b3aab8aed35d77644524c9402f6.png"/>
            </view>
            <view class="right">
              <view class="top">
                <text class="font-gray">{{ item.name_equip }}</text>
                <text class="font-gray">{{ dateFormat(item.overtime) }}</text>
              </view>
              <text class="multiline-ellipsis">已完成：{{ item.name_exper }}</text>
            </view>
          </view>
        </slider-item>
        <view class="__margin-top"></view>
      </scroll-view>
    </view>
    <view class="tools" :class="{ 'fade-in': edit, 'fade-out': !edit }">
      <view v-if="edit" class="wrap">
        <view class="tools-item" @click="selectOrAllselect">
          <uni-icons v-if="!selectAll" type="checkbox" size="40rpx"/>
          <text v-if="!selectAll" class="text">全选</text>
          <uni-icons v-if="selectAll" type="checkbox-filled" size="40rpx"/>
          <text v-if="selectAll" class="text">反选</text>
        </view>
        <view class="tools-item" @click="deleteAllOrSingle">
          <uni-icons type="trash" size="40rpx"></uni-icons>
          <text class="text">删除</text>
        </view>
        <view class="tools-item" @click="complete">
          <uni-icons type="checkmarkempty" size="40rpx"></uni-icons>
          <text class="text">完成</text>
        </view>
      </view>
    </view>
    <sv-intercept-back
        :show="edit"
        :beforeIntercept="beforeIntercept"
    />
  </view>
</template>

<script>
//查询实验完成信息
import {_experovermessage} from '@/service/exper_api.js'
//查看未读消息
import {
  _unreadmessage
} from '@/service/message.js'
import {
  _havereadmessage
} from '@/service/message.js'
//删除所有未读消息
import {
  _deleteallinform
} from '@/service/message.js'

//获取某用户收到的所有共享申请以及共享邀请
import {
  _allsharingapplyandinvite
} from "@/service/sharingequip.js"

//通过id删除消息列表
import {_deleteInformByID} from '@/service/message.js'
import ChunLeiPopups from "../../components/chunLei-popups/chunLei-popups.vue";
import UniNavBar from "@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-nav-bar.vue";
import UniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import SliderItem from "@/components/slider-item/slider-item.vue";

export default {
  components: {SliderItem, UniIcons, UniNavBar, ChunLeiPopups},
  data() {
    return {
      scrollTop: 0,
      old: {
        scrollTop: 0
      },
      experovermsg: [],
      account_user: '',
      sharingmsg: '',
      sharemsg: [],
      sharetext: '',
      serialnum_history: '',

      editmore: false,//弹框是否隐藏 初始状态为隐藏
      edit: false,//是否处于编辑模式
      allselect: false,//选择全部实验进行删除
      cancel: false,//取消文字是否隐藏
      selectAll: false,//切换“反选”与“全选”的样式
      idToDelete: {},//用于存储点击列表的id用于删除列表
    };
  },
  onLoad() {
    let newdata;
    try {
      const value = uni.getStorageSync('userInfo');
      if (value != null) {
        this.account_user = value.accountNum;
        console.log(this.account_user)
      }
    } catch (e) {
      console.error(e)
    }
    this.getexpermsg()
    this.unreadmessage()
    this.havereadmessage()
    this.getTitleText()
    this.allapplyandinvite()

  },
  methods: {
    beforeIntercept() {
      this.edit = false;
    },
    toEdit(e) {
      this.edit = true;
      // console.log(this.edit)
    },
    scroll: function (e) {
      // console.log(e)
      this.old.scrollTop = e.detail.scrollTop
    },
    navTo(url) {
      uni.navigateTo({
        url: url,
        success(res) {
          console.log("成功", res)
        },
        fail(res) {
          console.log("失败", res)
        }
      })
    },

    //所有共享申请和共享邀请
    async allapplyandinvite() {
      console.log('申请共享')
      let data = {
        account_sharingequip: this.account_user
      }
      let res = await _allsharingapplyandinvite(data);
      this.sharemsg = res.data;
      console.log(this.sharemsg);
      this.getTitleText()
    },
    getTitleText() {
      console.log(this.sharemsg.length)
      for (let i = 0; i < this.sharemsg.length; i++) {
        console.log('lalalalala')
        console.log(this.sharemsg[i])
        if (this.sharemsg[i].type_sharingequip === '3') {
          this.sharetext = "用户" + this.sharemsg[i].nickname_user + "向您申请" + this.sharemsg[i].name_equip + "的共享";

        } else if (this.sharemsg[i].type_sharingequip === '2') {
          this.sharetext = "账号******" + this.sharemsg[i].account_bindequip.substr(-4) + "的用户邀请您共享设备：" + this.sharemsg[i].name_equip;
        }
        console.log(this.sharetext)
      }
    },
    async unreadmessage() {
      console.log(111)
      try {
        console.log(this.account_user);
        let data = {
          receiver: this.account_user
        }
        let temp = await _unreadmessage(data);
        console.log(temp);
      } catch (e) {
        console.log(e);
        throw e;
      }
    },
    async havereadmessage() {
      let data = {
        receiver: this.account_user
      }
      let res = await _havereadmessage(data)
      console.log(res.data)
    },

    dateFormat(registertime) {
      let date = new Date(registertime);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hours = date.getHours();
      let minutes = date.getMinutes();
      let seconds = date.getSeconds();
      return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    },
    async getexpermsg() {
      let data = {
        account_user: this.account_user
      }
      let res = await _experovermessage(data)
      console.log(res.data)
      this.experovermsg = res.data
    },

    async deleteInform() {
      try {
        for (let i in this.idToDelete) {
          let res = await _deleteInformByID({
            id_user: i
          });
          if (res.flag) {
            console.log('删除成功！');
          }
        }
        uni.redirectTo({
          url: '/pages/inform1/inform1'
        })
      } catch (e) {
        console.log(e);
      }
    },
    deletetankuang() {
      const self = this
      uni.showModal({
        title: '提示',
        // 提示文字
        content: '是否删除所选信息',
        // 取消按钮的文字自定义
        cancelText: "取消",
        // 确认按钮的文字自定义
        confirmText: "确定",
        //删除字体的颜色
        confirmColor: 'red',
        //取消字体的颜色
        cancelColor: '#000000',
        success: async (res) => {
          if (res.confirm) {
            await self.deleteInform(); // await here to ensure completion before proceeding
          }
        }
      })
    },
    //点击删除图标删除所有或多个实验数据
    deleteAllOrSingle() {
      if (Object.keys(this.idToDelete).length === 0) {
        this.$api.msg('请选择需要删除的实验！');
        return;
      }
      this.deletetankuang()
    },

    toggleImage(index, item) {
      if (!this.edit) {
        this.navTo('/pages/expertrecord/expertrecord?serialnum_history=' + item.serialnum_history)
        return;
      }

      let {selected = false, ...options} = this.experovermsg[index];
      // 使用 Vue 的 $set 方法来更新数组中指定索引位置的对象
      this.$set(this.experovermsg, index, {
        // 创建新的对象，保留原有属性，同时将 selected 属性取反
        ...options,
        selected: !selected
      });
      console.log(this.experovermsg[index])

      if (this.experovermsg[index].selected) {
        this.idToDelete[this.experovermsg[index].id_user] = index;
      } else {
        delete this.idToDelete[this.experovermsg[index].id_user];
      }
      if (this.selectAll) {
        this.selectAll = false;
      }
      console.log(JSON.stringify(this.idToDelete))
    },
    //点击全选按钮后选中与不选中列表的逻辑
    selectOrAllselect() {
      if (!this.selectAll) {
        for (let i in this.experovermsg) {
          this.experovermsg[i].selected = true;
          this.idToDelete[this.experovermsg[i].id_user] = i;
        }
        this.selectAll = true;
      } else {
        for (let i in this.experovermsg) {
          this.experovermsg[i].selected = false;
          this.idToDelete = {};
        }
        this.selectAll = false;
      }
      console.log(JSON.stringify(this.idToDelete))
      this.experovermsg = JSON.parse(JSON.stringify(this.experovermsg));
    },
    complete() {
      this.edit = false;
      for (let i in this.idToDelete) {
        this.experovermsg[this.idToDelete[i]].selected = false;
      }
      this.idToDelete = {};
    }
  }
};
</script>

<style scoped lang="scss">

.list-wrap {
  background-color: #e5e5e569;

  .list {
    //#ifdef APP-PLUS
    height: 100vh;
    //#endif
    //#ifdef H5
    height: calc(100vh - 44px);
    //#endif
    box-sizing: border-box;
    padding: 0 30rpx; //上 左 下 右
  }

  .__margin-top {
    height: 20rpx;
  }

  .section:nth-child(2) {
    margin-top: 0;
  }

  .section:last-child {
    margin-bottom: 20rpx;
  }

  .section {
    padding: 30rpx;
    background-color: #ffffff;
    border-radius: 30rpx;
    margin-top: 20rpx;
    display: flex;
    flex-direction: column;
    transition: background-color 0.25s;

    &:active {
      background-color: #f0f0f0; // 高亮背景色
    }

    .section-content {
      height: 100%;
      display: flex;

      .left {
        width: 20%;
        display: flex;
        align-items: center;
        justify-content: center;

        .icon {
          width: 70rpx;
          height: 70rpx;
        }
      }

      .right {
        width: 80%;
        display: flex;
        flex-direction: column;
        justify-content: space-around;

        .top {
          display: flex;
          justify-content: space-between;

          .font-gray {
            font-size: 20rpx;
            color: #38383899;
          }
        }
      }

      .multiline-ellipsis {
        display: -webkit-box;
        -webkit-line-clamp: 1; /* 控制显示的行数 */
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}

.tools {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 100rpx;
  background-color: #ffffff;
  transition: all 0.25s ease-in-out; /* 添加过渡效果 */

  .wrap {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }

  &.fade-out {
    opacity: 0;
    height: 0;
    transform: translateY(100%); /* 向下移动 */
  }

  &.fade-in {
    opacity: 1;
    transform: translateY(0); /* 回到原位 */
  }

  /* tools-item 的样式 */
  .tools-item {
    width: 15%;
    display: flex;
    flex-direction: column;
    align-items: center;

    &:active {
      background-color: #e0e0e0; /* 点击时背景色变化 */
      transition: background-color 0.25s;
    }
  }

  .text {
    font-size: 30rpx;
  }
}
</style>